/*
   Copyright (c) 2016 VMware, Inc. All Rights Reserved.
   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package main

import (
	"github.com/astaxie/beego"
	"github.com/vmware/harbor/src/common/dao"
	"github.com/vmware/harbor/src/common/models"
	"github.com/vmware/harbor/src/common/utils/log"
	"github.com/vmware/harbor/src/jobservice/job"
)

func main() {
	//注册数据库
	dao.InitDatabase()
	//初始化路由
	initRouters()
	//初始化worker
	job.InitWorkerPool()
	//监听jobQueue,如果jobQueue里有任务就取出一个worker来处理
	go job.Dispatch()
	//Harbor在调度过程中有可能存在异常情况,如镜像复制到一半停电了,此时镜像状态为Running状态,
	//所以重新运行jobserver时，需要把Running和Retrying状态的镜像给重新调度
	resumeJobs()
	//运行后台守护程序
	beego.Run()
}

//重新调度Pending,Retrying状态的镜像
func resumeJobs() {
	log.Debugf("Trying to resume halted jobs...")
	//把(Running)状态修改为(Pending)
	err := dao.ResetRunningJobs()
	if err != nil {
		log.Warningf("Failed to reset all running jobs to pending, error: %v", err)
	}
	//Pending状态和Retrying状态的镜像重新调度
	jobs, err := dao.GetRepJobByStatus(models.JobPending, models.JobRetrying)
	if err == nil {
		for _, j := range jobs {
			log.Debugf("Resuming job: %d", j.ID)
			//丢给worker去重新调度
			job.Schedule(j.ID)
		}
	} else {
		log.Warningf("Failed to jobs to resume, error: %v", err)
	}
}
